-- UIDungeonAchiv
-- Created by chengb Jul/12/2015
-- 迷宫成就（迷宫事件）界面

require "game/ui/form/achievement/UIAchivBonusInfo"

UIDungeonAchiv = class("UIDungeonAchiv", function()
    return cc.Layer:create();
end);

function UIDungeonAchiv.create(dungeonId)
    return UIDungeonAchiv.new(dungeonId);
end

-- 构造函数
function UIDungeonAchiv:ctor(dungeonId)
    self:setName("UIDungeonAchiv");

    -- 初始化
    local node = cc.CSLoader:createNode("layout/achievement/DungeonAchiv.csb");
    self:addChild(node);
    self.node = node;

    self.dungeonId = dungeonId;
    self.achivList = self:getAchivList();

    -- 在迷宫内打开，设置Z轴
    if DungeonM.isInDungeon() then
        self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);
    end

    -- 注册点击事件
    self:registerTouchEvent();

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 适配
function UIDungeonAchiv:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 重绘
function UIDungeonAchiv:redraw()
    -- 关卡名称
    local dungeonName = DungeonAreaM.query(self.dungeonId, "name");
    local dungeonNameLabel = findChildByName(self.node, "CT/dungeon_name");
    TextStyleM.setTextStyle(dungeonNameLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_ORANGE, true, -4, nil, nil, nil, nil, true);
    TextStyleM.setShadowStyle(dungeonNameLabel, cc.size(0, -2.8));
    dungeonNameLabel:setString(dungeonName);

    -- 重绘dp信息
    self:redrawDpInfo();

    -- 重绘成就信息列表
    self:redrawAhivList();

    -- 重绘领奖按钮状态
    self:redrawBonusButton();

    -- 如果是在迷宫内打开，领取按钮隐藏
    if DungeonM.isInDungeon() and not DungeonM.isPause() then
        local btnBonus = findChildByName(self.node, "BT/btn_bonus");
        btnBonus:setVisible(false);
    end
end

-- 重绘dp信息
function UIDungeonAchiv:redrawDpInfo()
    -- dp信息
    local curDp = AchievementM.calcCurDp(self.dungeonId);
    local bonusDp = AchievementM.getCurBonusDpValue(self.dungeonId) or -1;
    local dpInfoLabel = findChildByName(self.node, "CT/dp_info");
    TextStyleM.setTextStyle(dpInfoLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_ORANGE, true, -4, nil, nil, nil, nil, true);
    dpInfoLabel:setString(string.format("%d/%d", curDp, bonusDp));

    -- dp冒泡
    local dpBubbleImg = findChildByName(self.node, "CT/dp_bubble");
    local nextDp = AchievementM.canTakeBonus(self.dungeonId);
    if nextDp then
        -- dp值未满，播放气泡动画
        playBubbleAnima(dpBubbleImg, false);
    else
        dpBubbleImg:stopAllActions();
    end
end

-- 重绘领奖按钮状态
function UIDungeonAchiv:redrawBonusButton()
    local btnBonus = findChildByName(self.node, "BT/btn_bonus");
    local hintNode = findChildByName(btnBonus, "hint");
    local canGetNum = AchievementM.getAvailableBonusNum(self.dungeonId);
    checkBlueBubbleStatus(hintNode, canGetNum);

    -- if canGetNum > 0 then
        -- 满足领取条件时，按钮高亮
        -- setButtonEnabled(btnBonus, true);
    -- else
        -- setButtonEnabled(btnBonus, false);
    -- end
end

-- 获取排序后的成就信息列表
function UIDungeonAchiv:getAchivList()
    -- 获取该迷宫的所有成就编号
    local achivIdList = AchievementM.getIdsByDungeonId(self.dungeonId);

    local achivList = {};
    for _, id in pairs(achivIdList) do
        table.insert(achivList, AchievementM.query(id));
    end

    -- 规则：优先按照sort_priority排，sort_priority相同时再按照id排
    -- 注意：由于滚动容器是由下到上遍历的，因此需要逆序一下
    local function sortFunc(info1, info2)
        if info1.sort_priority == info2.sort_priority then
            return info1.id < info2.id;
        else
            return info1.sort_priority < info2.sort_priority;
        end
    end

    table.sort(achivList, sortFunc);
    return achivList;
end

-- 重绘成就信息列表
function UIDungeonAchiv:redrawAhivList()
    local scrollview = findChildByName(self.node, "CT/scrollview");
    scrollview:removeAllChildren();
    scrollview:jumpToTop();

    local itemNode = cc.CSLoader:createNode("layout/achievement/DungeonAchivItem.csb");

    -- 刷新成就信息列表
    self.achivList = self:getAchivList();

    -- 图标间距(横向)
    local wGap = 0;

    -- 图标间距(纵向)
    local hGap = 0;

    -- 格子宽度
    local itemWidth = 0;

    -- 格子高度
    local itemHeight = 61;

    -- 左边距
    local leftWGap = -2;

    -- 行间距
    local topGap = 0;
    local bottomHGap = 0;

    -- 单页最大可容纳列数
    local MIN_GRID_COLUMN = 1;

    -- 获取记录总数
    local totalNum = #self.achivList;

    -- 初始化滚动条
    ScrollTool.initScrollGridsVertical(self, scrollview, itemNode, totalNum, MIN_GRID_COLUMN, wGap, hGap, itemWidth, itemHeight, topGap, bottomHGap, leftWGap, self.registerItemTouchEvent, self.InitAchiveItem);

    -- 添加滑块
    UIIndicator.attach(scrollview);
end

function UIDungeonAchiv:InitAchiveItem(child, index)
    local mConfig = self.achivList[index];
    local id = mConfig.id;
    child.id = id;

    local config = AchievementM.query(id);

    -- 显示成就图标
    local icon = config["icon"];
    local iconImg = findChildByName(child, "icon");
    iconImg:loadTexture(getAchivIconPath(icon));

    -- 显示成就描述
    local desc = AchievementM.queryDesc(id);
    local descLabel = findChildByName(child, "desc");
    local dp = config["dp"];
    local dpLabel = findChildByName(child, "dp");

    -- 该项成就是否完成
    local isCompleted = AchievementM.isCompleted(id);
    local takenMarkImg = findChildByName(child, "taken_mask");

    -- 设置缩进
    local kerning = -1;

    -- 如果已经完成，用蓝色字体显示，否则用默认字体
    if isCompleted then
        TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BLUE, nil, kerning);
        TextStyleM.setTextStyle(dpLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BLUE, nil, kerning);

        -- 显示已完成的蒙版
        takenMarkImg:setVisible(true);
    else
        TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN, nil, kerning);
        TextStyleM.setTextStyle(dpLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN, nil, kerning);
        takenMarkImg:setVisible(false);
    end
    descLabel:setString(desc);
    dpLabel:setString(string.format("+%ddp", dp));

    return child;
end

-- 注册格子点击事件
function UIDungeonAchiv:registerItemTouchEvent(node)
    local touchImg = findChildByName(node, "icon");
    local function onBgClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            self:onChildClick(node);
        end
    end
    touchImg:addTouchEventListener(onBgClick);
end

-- 成就被点击的处理
function UIDungeonAchiv:onChildClick(child)
    local id = child.id;
    local title, tip;
    if AchievementM.query(id, "only_main_area") == 1 then
        -- 该成就仅对主关卡开放
        title = getLocStr("special_event");
        tip   = getLocStr("special_event_tip");
    else
        title = getLocStr("normal_event");
        tip   = getLocStr("normal_event_tip");
    end
    showHint2(title, tip);
end

-- 注册点击事件
function UIDungeonAchiv:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIDungeonAchiv");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 注册领奖按钮点击事件
    local btnBonus = findChildByName(self.node, "BT/btn_bonus");
    local function onBonusClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 打开dp奖励信息界面
            UIMgr.getCurrentScene():removeFormByName("UIAchivBonusInfo");
            local uiForm = UIAchivBonusInfo.create(self.dungeonId);
            UIMgr.getCurrentScene():addForm(uiForm);
            AudioM.playFx("ui_open1");
        end
    end
    btnBonus:addTouchEventListener(onBonusClick);
    TextStyleM.setTextStyle(btnBonus, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBonus:setTitleText(getLocStr("btn_text_dp_bonus"));

    -- 注册dp冒泡点击事件
    local dpBubbleImg = findChildByName(self.node, "CT/dp_bubble");
    local function onDpBubbleClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 获取下一个可领取奖励的dp值
            local nextDp = AchievementM.getNextBonusDp(self.dungeonId);
            if nextDp == nil then
                return;
            end

            -- 弹出提示
            local canGetNum = AchievementM.getAvailableBonusNum(self.dungeonId);
            if DungeonM.isInDungeon() and canGetNum > 0 then
                alert(getLocStr("dp_bonus_take_tip2"));
            else
                alert(string.format(getLocStr("dp_bonus_take_tip"), nextDp));
            end
        end
    end

    local boxImg = findChildByName(self.node, "CT/box");
    boxImg:setTouchEnabled(true);
end

-- 注册事件处理回调函数
function UIDungeonAchiv:registerEventCallback()
    -- 注册领取成就奖励的事件回调
    EventMgr.register("UIDungeonAchiv", event.TAKE_ACHIV_BONUS, function(args)

        -- 重绘dp信息
        self:redrawDpInfo();

        -- 重绘领奖按钮状态
        self:redrawBonusButton();
    end);

    -- 在迷宫信息界面打开该页面
    EventMgr.register("UIDungeonAchiv", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UIDungeonAchiv" then
            if DungeonM.isInDungeon() then
                UIMgr:getCurrentScene().topMenu:show(TOPMENU_FRAME_MONEY, TOPMENU_FRAME_GEM);
                UIMgr:getCurrentScene().topMenu:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 2);
            end
            local btNode = findChildByName(self.node, "BT");
            btNode:setVisible(true);

            UIMgr:getCurrentScene().topMenu:show(TOPMENU_FRAME_TREE, TOPMENU_FRAME_LIFE);
        elseif para["lose"] == "UIDungeonAchiv" then
            local btNode = findChildByName(self.node, "BT");
            btNode:setVisible(false);
        end
    end);

    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            cclog("UIDungeonAchiv 界面析构清理");
            EventMgr.removeAll("UIDungeonAchiv");

            if DungeonM.isInDungeon() then
                -- 还原TopMenu的ZOrder
                local topMenu = UIMgr:getCurrentScene().topMenu;
                if topMenu then
                    topMenu:setVisible(self.oldVisible);
                    topMenu:setLocalZOrder(self.oldZOrder);
                end
            end

        elseif ev == "enter" then
            if DungeonM.isInDungeon() then
                -- 临时调高TOP_MENU的ZOrder
                local topMenu = UIMgr:getCurrentScene().topMenu;
                self.oldVisible = topMenu:isVisible();
                UIMgr.getCurrentScene().topMenu:setVisible(true);
                self.oldZOrder = topMenu:getLocalZOrder();
            end
        end
    end);
end

function UIDungeonAchiv:hideOrShowBT(flag)
    local BT = findChildByName(self.node, "BT");
    BT:setVisible(flag);
end
